<template>
  <div class="product-management">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="肉类" :value="1" />
            <el-option label="蔬菜" :value="2" />
            <el-option label="水果" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增商品</el-button>
    </div>

    <!-- 搜索条件标签 -->
    <div class="search-tags" v-if="hasSearchConditions">
      <span class="search-tags-label">搜索条件：</span>
      <el-tag 
        v-if="searchForm.name" 
        closable 
        @close="clearSearchName"
        class="search-tag"
      >
        商品名称：{{ searchForm.name }}
      </el-tag>
      <el-tag 
        v-if="searchForm.categoryId !== null" 
        closable 
        @close="clearSearchCategory"
        class="search-tag"
      >
        商品分类：{{ getCategoryName(searchForm.categoryId) }}
      </el-tag>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="image" label="商品图片" width="100">
        <template #default="{ row }">
          <el-image 
            v-if="row.image"
            :src="row.image" 
            :preview-src-list="[row.image]"
            fit="cover"
            class="product-image"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" min-width="120" />
      <el-table-column prop="categoryId" label="分类" width="100">
        <template #default="{ row }">
          {{ getCategoryName(row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '在售' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            :type="row.status === 1 ? 'warning' : 'success'" 
            link 
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '下架' : '上架' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="padding: 0 20px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option label="肉类" :value="1" />
            <el-option label="蔬菜" :value="2" />
            <el-option label="水果" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="1.00" 
            :min="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="form.stock" 
            :min="0" 
            :step="1"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="product-uploader"
            :action="null"
            :show-file-list="true"
            :http-request="handleImageUpload"
            :before-upload="beforeImageUpload"
            :limit="1"
            list-type="picture-card"
            :multiple="false"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :file-list="fileList"
          >
            <el-icon v-if="!form.image"><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <div class="upload-tip">支持 jpg、png 格式，大小不超过 3MB</div>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue'
import { 
  getProductList, 
  addProduct, 
  updateProduct, 
  deleteProduct,
  toggleProductStatus,
  uploadProductImages
} from '@/api/product'

// 搜索表单
const searchForm = reactive({
  name: '',
  categoryId: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 表单对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref(null)
const form = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: 0,
  stock: 0,
  description: '',
  image: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const categoryMap = {
    1: '肉类',
    2: '蔬菜',
    3: '水果',
    4: '其他'
  }
  return categoryMap[categoryId] || '未知分类'
}

// 图片预览
const dialogImageUrl = ref('')
const dialogImageVisible = ref(false)

// 文件列表
const fileList = ref([])

// 图片上传相关方法
const handleImageUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('files', options.file)
    const res = await uploadProductImages(formData)
    if (res.code === 1 && res.data && res.data.length > 0) {
      const imageUrl = res.data[0]
      form.image = imageUrl
      fileList.value = [{
        name: options.file.name,
        url: imageUrl
      }]
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(res.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

const handleExceed = () => {
  ElMessage.warning('只能上传 1 张图片')
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt3M = file.size / 1024 / 1024 < 3

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt3M) {
    ElMessage.error('图片大小不能超过 3MB!')
    return false
  }
  return true
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogImageVisible.value = true
}

const handleRemove = (file) => {
  form.image = ''
  fileList.value = []
}

// 获取商品列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getProductList({
      name: searchForm.name,
      categoryId: searchForm.categoryId,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    const { records, total: totalCount } = res.data
    tableData.value = records
    total.value = totalCount
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.categoryId = null
  handleSearch()
}

// 新增商品
const handleAdd = () => {
  isAdd.value = true
  dialogTitle.value = '新增商品'
  dialogVisible.value = true
  Object.assign(form, {
    id: null,
    name: '',
    categoryId: null,
    price: 0,
    stock: 0,
    description: '',
    image: '',
    status: 1
  })
  // 清空文件列表
  fileList.value = []
}

// 编辑商品
const handleEdit = (row) => {
  isAdd.value = false
  dialogTitle.value = '编辑商品'
  dialogVisible.value = true
  // 深拷贝数据，避免直接修改原数据
  Object.assign(form, JSON.parse(JSON.stringify(row)))
  // 设置文件列表
  fileList.value = row.image ? [{
    name: '商品图片',
    url: row.image
  }] : []
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该商品吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteProduct(row.id)
        if (res.code === 1) {
          ElMessage.success('删除成功')
          getList()
        }
      } catch (error) {
        console.error('删除商品失败:', error)
        ElMessage.error('删除商品失败')
      }
    })
    .catch(() => {})
}

// 切换商品状态
const handleToggleStatus = (row) => {
  const actionText = row.status === 1 ? '下架' : '上架'
  ElMessageBox.confirm(`确认${actionText}该商品吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await toggleProductStatus(row.id)
        if (res.code === 1) {
          ElMessage.success(`${actionText}成功`)
          getList()
        }
      } catch (error) {
        console.error(`${actionText}失败:`, error)
        ElMessage.error(`${actionText}失败`)
      }
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const api = isAdd.value ? addProduct : updateProduct
        // 构建提交的数据对象
        const submitData = {
          ...form,
          createTime: form.createTime || new Date().toISOString().replace('T', ' ').split('.')[0],
          updateTime: new Date().toISOString().replace('T', ' ').split('.')[0],
          isFavorite: form.isFavorite || 0,
          // 确保图片URL被包含在提交数据中
          image: form.image || ''
        }
        console.log('提交的数据：', submitData) // 添加日志
        const res = await api(submitData)
        if (res.code === 1) {
          ElMessage.success(isAdd.value ? '新增成功' : '更新成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.msg || (isAdd.value ? '新增失败' : '更新失败'))
        }
      } catch (error) {
        console.error(isAdd.value ? '新增商品失败:' : '更新商品失败:', error)
        ElMessage.error(isAdd.value ? '新增商品失败' : '更新商品失败')
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  fileList.value = []
  form.image = ''
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 判断是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.name || searchForm.categoryId !== null
})

// 清除商品名称搜索条件
const clearSearchName = () => {
  searchForm.name = ''
  handleSearch()
}

// 清除商品分类搜索条件
const clearSearchCategory = () => {
  searchForm.categoryId = null
  handleSearch()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.product-management {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.product-uploader {
  text-align: center;
}

.product-uploader :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

.product-uploader :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}

.product-uploader :deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.search-tags {
  margin-bottom: 20px;
}

.search-tags-label {
  margin-right: 8px;
  color: #606266;
}

.search-tag {
  margin-right: 8px;
}
</style> 